#include <SPI.h>
#include <chipKITEthernet.h>
#include <string.h>

/*
  This sketch is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This sketch is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this sketch; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
/************************************************************************/
/*  Revision History:							*/
/* 									*/
/* 8/08/2011 Digilent Inc. (KeithV)					*/
/* Updated for use with the chipKIT Max32 and chipKIT Network Shield	*/
/*									*/
/************************************************************************/

/*
  Web  Server
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe
 
 */

// Enter a MAC address and IP address for your controller below. 
// A zero MAC address means that the chipKIT MAC is to be used
byte mac[] = {  
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 

//       !!MODIFY THIS!!
// The IP address will be dependent on your local network:
byte ip[] = { 
  192,168,1,2 };

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
Server server(80);

char cmd[15];    // Nothing magical about 15, increase these if you need longer commands/parameters
char param1[15];
char param2[15];

void setup()
{
  // start the Ethernet connection and the server:
  //Ethernet.begin(mac, ip);
  Ethernet.begin();  // this will use DHCP
  server.begin();
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.println("void Setup()");
}

#define bufferMax 128
int bufferSize;
char buffer[bufferMax];

//Serial.print("Entering loop...");
void loop()
{
    // listen for incoming clients
  String knapp;
  Client client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    bufferSize = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          Serial.println("Caling ParseRecievedRequest()");
          knapp = "<input type=""button" "value=""Knapp!>";
          client.print(knapp);
          ParseReceivedRequest();
          
          /*
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(analogRead(analogChannel));
            client.println("<br />"
            
          }
          */
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        /*
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }*/
        else if (bufferSize < bufferMax) {
          currentLineIsBlank = false;
          buffer[bufferSize++] = c; 
        }
      }
    }
    
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
}

void ParseReceivedRequest()
{
  Serial.println("in ParseReceivedRequest");
  Serial.println(buffer);
  
  //Received buffer contains "GET /cmd/param1/param2 HTTP/1.1".  Break it up.
  char* slash1;
  char* slash2;
  char* slash3;
  char* space2;
  
  Serial.println("variables inicilized..");
  Serial.println("Look for first slash");
  slash1 = strstr(buffer, "/") + 1; // Look for first slash
    Serial.println("Look for second slash");
  slash2 = strstr(slash1, "/") + 1; // second slash
    Serial.println("Look for third slash");
  slash3 = strstr(slash2, "/") + 1; // third slash
    Serial.println("Space after second slash...");
  space2 = strstr(slash2, " ") + 1; // space after second slash (in case there is no third slash)
  if (slash3 > space2) slash3=slash2;
  
  Serial.println("URL splitted..");
  
  PrintString("slash1",slash1);
  PrintString("slash2",slash2);
  PrintString("slash3",slash3);
  PrintString("space2",space2);
  
  
  // strncpy does not automatically add terminating zero, but strncat does! So start with blank string and concatenate.
  cmd[0] = 0;
  param1[0] = 0;
  param2[0] = 0;
  strncat(cmd, slash1, slash2-slash1-1);
  strncat(param1, slash2, slash3-slash2-1);
  strncat(param2, slash3, space2-slash3-1);
  
  PrintString("cmd",cmd);
  PrintString("param1",param1);
  PrintString("param2",param2);
  
}

void PerformRequestedCommands()
{
  if ( strcmp(cmd,"digitalWrite") == 0 ) RemoteDigitalWrite();
  //if ( strcmp(cmd,"analogRead") == 0 ) RemoteAnalogRead();
}

void RemoteDigitalWrite()
{
  Serial.println("RemoteDigitalWrite");
  int ledPin = param1[0] - '0'; // Param1 should be one digit port
  int ledState = param2[0] - '0'; // Param2 should be either 1 or 0
  digitalWrite(ledPin, LOW);   // set the LED on
  delay(1000);              // wait for a second
  digitalWrite(ledPin, ledState);    // set the LED off
  delay(1000);              // wait for a second
}

void PrintString(char* label, char* str)
{
  Serial.print(label);
  Serial.print("=");
  Serial.println(str);
}
